#ifndef CCLIENTPULL_H
#define CCLIENTPULL_H

#include <QFile>
#include <QObject>
#include <QTcpSocket>
#include <QUdpSocket>
#include "Sdp.h"
#include "RtspManager.h"

class CPullClient : public QObject
{
    Q_OBJECT

signals:
    void connected();
    void disconnected();

    void recvMsg(const QByteArray &msg);

    void sendRtpData(const QByteArray &data, int streamId);
    void sendRtcpData(const QByteArray &data);

    void sendSdp(Sdp *sdp);

public:
    explicit CPullClient(QObject *parent = nullptr);
    ~CPullClient();

public slots:
    void onStartConnect(const QString &url);
    void onEndConnect(); // 断开连接并发出信号

protected:
    void timerEvent(QTimerEvent *event) override;

private:
    QTcpSocket *m_rtspTcp{nullptr};

    QUdpSocket *m_rtpUdp{nullptr};
    QUdpSocket *m_rtcpUdp{nullptr};

    QByteArray m_rtpBuf;

    QFile *m_file{nullptr};
    QTextStream m_stream;

    RtspManager m_rtspManager;
    uint32_t rtcp_ssrc{0};
    uint32_t video_ssrc{0};
    uint32_t audio_ssrc{0};

    uint64_t recv_rtp_count{0};

    uint16_t curVideoSeq{0};
    uint16_t curAudioSeq{0};

    uint32_t curVideoSsrc{0};
    uint32_t curAudioSsrc{0};

    QMap<uint16_t, QByteArray> m_videoCache;
    QMap<uint16_t, QByteArray> m_audioCache;

    bool sendCmd(const QByteArray &cmd);
    void writeToLog(const QString &data);

    int rtspTimerId{0};
    void killRtspTimer();                 // 关闭当前定时器并将id设为0
    void reStartRtspTimer(int ms = 1000); // 关闭当前定时器并重新启动定时器

    bool isSendSdp{false};

    void analyzeRtpData(const QByteArray &data);
    void analyzeRtcpData(const QByteArray &data);
private slots:
    void recvRtspMsg();
};

#endif // CCLIENT_PULL_H
